package com.bjt.wms.sys.controller;

import cn.hutool.core.date.DateUtil;
import com.bjt.common.config.paragetter.BasePageRequest;
import com.bjt.utils.R;
import com.bjt.wms.sys.model.DeliverySheet;
import com.bjt.wms.sys.service.ExcelService;
import com.bjt.wms.sys.service.DeliverySheetService;
import com.jfinal.aop.Inject;
import com.jfinal.core.Controller;
import com.jfinal.kit.Kv;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;

import java.io.File;

/**
 * @author WenbinJi
 * <p>
 * 配货单管理
 */
public class DeliverySheetController extends Controller {

    @Inject
    private DeliverySheetService deliverySheetService;

    @Inject
    private ExcelService excelService;

    /**
     * 分页查询
     */
    public void queryList(BasePageRequest<DeliverySheet> basePageRequest) {

        Kv cond = Kv.create();
        if (StrKit.notBlank(getPara("code"))) {
            cond.set("code", getPara("code"));
        }
        if (StrKit.notBlank(getPara("warehouse"))) {
            cond.set("dept", getPara("dept"));
        }
        if (StrKit.notBlank(getPara("duty"))) {
            cond.set("duty", getPara("duty"));
        }

        renderJson(deliverySheetService.queryList(basePageRequest, cond));
    }

    public void save() {
        DeliverySheet deliverySheet = getModel(DeliverySheet.class, "");
        if (deliverySheet.getId() == null) {
            deliverySheet.setState("未完成");
            deliverySheet.setEnable("是");
            deliverySheet.setCreateTime(DateUtil.date().toString("yyyy-MM-dd HH:mm:ss"));
            renderJson(deliverySheet.save() ? R.ok() : R.error("保存信息失败"));
        } else {
            renderJson(deliverySheet.update() ? R.ok() : R.error("保存信息失败"));
        }
    }

    public void enable() {
        DeliverySheet deliverySheet = getModel(DeliverySheet.class, "");
        renderJson(deliverySheet.update() ? R.ok() : R.error("保存信息失败"));
    }

    public void delete() {
        String[] idArray = getParaValues("id");
        String ids = StrKit.join(idArray, ",");
        renderJson(Db.update("delete from delivery_sheet where id in (" + ids + ")") > 0 ? R.ok() : R.error("删除信息失败"));
    }

    public void toExcel() {
        DeliverySheet deliverySheet = DeliverySheet.dao.findById(getParaToInt("delivery_sheet_id"));

        try {
            String filePath = excelService.generateDeliverySheetExcel(deliverySheet);
            renderFile(new File(filePath));
        } catch (Exception ex) {
            renderJson(R.error().put("msg", ex.getMessage()));
        }
    }
}
